package cn.fulong.frame.service.impl;

import cn.fulong.frame.service.ComputeData;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("computeDataByExtend")
public class ComputeDataByExtend extends ComputeData {

    @Override
    public Map execute(Map datas, Map compute) throws Exception {
        String id = compute.get("id").toString();
        String id1 = id.split("=")[0];
        String id2 = id.split("=")[1];
        String ds1 = id1.split("\\.")[0];
        String code1 = id1.split("\\.")[1];
        String ds2 = id2.split("\\.")[0];
        String code2 = id2.split("\\.")[1];
        List<Map> data1 = (List<Map>) datas.get(ds1);
        if (data1 == null || data1.size() == 0) {
            return null;
        }

        Map result = new HashMap();
        String name = compute.get("name").toString();

        List<Map> data2 = (List<Map>) datas.get(ds2);
        if (data2 == null || data2.size() == 0) {
            result.put(name, data1);
            return result;
        }

        Map newData2 = new HashMap();
        for (Map map : data2) {
            newData2.put(map.get(code2), map);
        }

        List<Map> newData1 = new ArrayList<>();
        for (Map map1 : data1) {
            Object key = map1.get(code1);
            Map map2 = (Map) newData2.get(key);
            if (map2 != null && map2.size() > 0) {
                map1.putAll(map2);
            }
            newData1.add(map1);
        }
        result.put(name, newData1);
        return result;
    }
}
